﻿using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Net.Http;
using System.Runtime.Serialization;
using System.Security.Cryptography;
using Newtonsoft.Json;
using ZL.Web.Utility.Config;
using ZLWeb.WebApiEntityBas;
using ZLWeb.WebApiEntityBase;

namespace ZL.Web.Utility.Http
{
    public class HttpHelper
    {
        /// <summary>
        ///     URL拼接
        /// </summary>
        /// <param name="url"></param>
        /// <param name="ClientName"></param>
        /// <param name="ClientVersion"></param>
        /// <param name="RandomCode"></param>
        /// <param name="version"></param>
        /// <returns></returns>
        public static Dictionary<string, string> HttpHeaderHandler(IdentityEntity iIdentityEntity)
        {
            string guid = Guid.NewGuid().ToString();
            if (ZLConfig.TokenKey == null)
            {
                string key = string.Format("{0}@{1}",
                    iIdentityEntity.ClientName, guid);
                string Token = DigestHelper.MD5Converter(key);
                return new Dictionary<string, string>
                    {
                        {"clientname", iIdentityEntity.ClientName},
                        {"passport", iIdentityEntity.Passport},
                        {"passporttype", iIdentityEntity.PassportType},
                        {"accesstoken", Token},
                        {"requestguid", guid}
                    };
            }
            if (!string.IsNullOrEmpty(iIdentityEntity.Passport) &&
                !string.IsNullOrEmpty(iIdentityEntity.PassportType))
            {
                string key = string.Format("{0}@{1}@{2}@{3}", iIdentityEntity.PassportType, iIdentityEntity.Passport,
                    ZLConfig.TokenKey, guid);
                string Token = DigestHelper.MD5Converter(key);
                return new Dictionary<string, string>
                {
                    {"clientname", iIdentityEntity.ClientName},
                    {"accesstoken", Token},
                    {"requestguid", guid},
                    {"passport", iIdentityEntity.Passport},
                    {"passporttype", iIdentityEntity.PassportType}
                };
            }
            else
            {
                string key = string.Format("{0}@{1}",
                    ZLConfig.TokenKey, guid);
                string Token = DigestHelper.MD5Converter(key);
                return new Dictionary<string, string>
                {
                    {"clientname", iIdentityEntity.ClientName},
                    {"accesstoken", Token},
                    {"requestguid", guid}
                };
            }
        }


        /// <summary>
        ///     http get 请求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <param name="getStrFunc"></param>
        /// <param name="customeRequestHeaders"></param>
        /// <returns></returns>
        public static T HttpRequestGet<T>(string url, Dictionary<string, string> customeRequestHeaders,
            Func<HttpContent, string> getStrFunc
            ) 
        {
            using (var http = new HttpClient())
            {
                http.Timeout = new TimeSpan(0, 0, 0, 30);
                foreach (var herader in customeRequestHeaders)
                {
                    if (http.DefaultRequestHeaders.Contains(herader.Key))
                    {
                        http.DefaultRequestHeaders.Remove(herader.Key);
                    }
                    http.DefaultRequestHeaders.Add(herader.Key, herader.Value);
                }
                var Result = http.GetAsync(url).Result;
                var Deresponsejson = getStrFunc(Result.Content);

                if (!Deresponsejson.Contains("无法连接"))
                {
                    try
                    {
                        var lists = JsonConvert.DeserializeObject<T>(Deresponsejson);
                        if (lists is ResponseResultInfo)
                        {
                            ResponseResultInfo item = lists as ResponseResultInfo;
                            item.Httpcode = Result.StatusCode.GetHashCode();
                        }
                        return lists;
                    }
                    catch (JsonException)
                    {
                        throw new CommonException(Deresponsejson);
                    }

                }
                else
                {
                    throw new CommonException(Deresponsejson);
                }
            }
        }

        /// <summary>
        ///     http Post 请求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <param name="httpContent"></param>
        /// <param name="getStrFunc"></param>
        /// <returns></returns>
        public static T HttpRequestPost<T>(string url, Dictionary<string, string> customeRequestHeaders,
            HttpContent httpContent,
            Func<HttpContent, string> getStrFunc)
        {

            using (var http = new HttpClient())
            {
                http.Timeout = new TimeSpan(0, 0,1, 30);
                foreach (var herader in customeRequestHeaders)
                {
                    if (http.DefaultRequestHeaders.Contains(herader.Key))
                    {
                        http.DefaultRequestHeaders.Remove(herader.Key);
                    }


                    http.DefaultRequestHeaders.Add(herader.Key, herader.Value);
                }
                var Result = http.PostAsync(url, httpContent).Result;
                var Deresponsejson = getStrFunc(Result.Content);

                if (!Deresponsejson.Contains("无法连接"))
                {
                    try
                    {
                        var lists = JsonConvert.DeserializeObject<T>(Deresponsejson);
                        if (lists is ResponseResultInfo)
                        {
                            ResponseResultInfo item = lists as ResponseResultInfo;
                            item.Httpcode = Result.StatusCode.GetHashCode();
                        }
                        return lists;
                    }
                    catch (JsonException)
                    {
                        throw new CommonException(Deresponsejson);
                    }
                }
                else
                {
                    throw new CommonException(Deresponsejson);
                }


            }


        }

    }
}